//
// Created by pengmutian on 2025/9/30.
//

#include "JNIEnvAutoRelease.h"
#include <jni.h>

class JNIEnvAutoRelease {
public:
    JNIEnvAutoRelease(JavaVM *jvm) : jvm_(jvm), env_(nullptr), needDetach_(false) {
        if (jvm_->GetEnv(reinterpret_cast<void **>(&env_), JNI_VERSION_1_6) == JNI_EDETACHED) {
            jvm_->AttachCurrentThread(&env_, nullptr);
            needDetach_ = true;
        }
    }

    ~JNIEnvAutoRelease() {
        if (needDetach_) {
            jvm_->DetachCurrentThread();
        }
    }

    JNIEnv *operator->() { return env_; }

    JNIEnv *get() { return env_; }

private:
    JavaVM *jvm_;
    JNIEnv *env_;
    bool needDetach_;

};